package main

import (
	"fmt"
	"log"

	"enterprise-base/internal/config"
	"enterprise-base/internal/middleware"
	"enterprise-base/internal/models"
	"enterprise-base/internal/routers/admin"
	"enterprise-base/internal/task"
	"enterprise-base/internal/utils"

	"github.com/gin-gonic/gin"
)

func main() {
	// 初始化Redis
	err := utils.InitRedis()
	if err != nil {
		log.Fatal("Failed to initialize redis:", err)
	}
	// dbURL := "postgres://username:password@localhost/dbname?sslmode=disable"
	dbURL := fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=disable", config.GlobalDataBaseConfig.Username, config.GlobalDataBaseConfig.Password, config.GlobalDataBaseConfig.Host, config.GlobalDataBaseConfig.Port, config.GlobalDataBaseConfig.Dbname)
	// 初始化数据库连接
	if err := utils.InitializeDB(dbURL); err != nil {
		log.Fatalf("Failed to initialize database: %v", err)
	}
	defer utils.CloseDB()

	// 生产模式
	// gin.SetMode(gin.ReleaseMode)
	// 强制日志颜色化
	gin.ForceConsoleColor()

	r := gin.Default()
	// 设置安全页眉中间件
	r.Use(setupSecurityHeaders())
	// 注册全局异常捕获中间件
	r.Use(globalPanicRecoveryMiddleware())
	// 设置路由
	r.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{"message": "Hello, World!"})
	})

	// 添加jwt鉴权中间件
	// r.Use(middleware.JWTAuthMiddleware())

	// 添加 admin 功能的路由组
	registerRoutes(r.Group("/admin"), admin.SetupRouter())

	// 添加一个全局的 404 处理函数
	r.NoRoute(func(c *gin.Context) {
		c.JSON(200, gin.H{
			"code": 404,
			"msg":  "404",
		})
	})
	// 初始化并启动定时任务
	task.InitCron()
	// 启动服务器
	err = r.Run(fmt.Sprintf("%s:%s", config.GlobalServerConfig.Host, config.GlobalServerConfig.Port))
	if err != nil {
		return
	}
}

// 注册路由
func registerRoutes(group *gin.RouterGroup, routes []models.RouteInfo) {
	for _, route := range routes {
		var handlers []gin.HandlerFunc
		if !route.NoAuth {
			// 首先添加鉴权中间件
			handlers = append(handlers, middleware.JWTAuthMiddleware())
		}
		// 如果有权限要求 再添加权限中间件
		// 然后添加原始处理器
		handlers = append(handlers, route.Handler)
		group.Handle(route.Method, route.Path, handlers...)
	}
}

// 设置安全页眉的中间件
func setupSecurityHeaders() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("X-Frame-Options", "DENY")
		c.Header("Content-Security-Policy", "default-src 'self'; connect-src *; font-src *; script-src-elem * 'unsafe-inline'; img-src * data:; style-src * 'unsafe-inline';")
		c.Header("X-XSS-Protection", "1; mode=block")
		c.Header("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload")
		c.Header("Referrer-Policy", "strict-origin")
		c.Header("X-Content-Type-Options", "nosniff")
		c.Header("Permissions-Policy", "geolocation=(),midi=(),sync-xhr=(),microphone=(),camera=(),magnetometer=(),gyroscope=(),fullscreen=(self),payment=()")
		c.Next()
	}
}

// globalPanicRecoveryMiddleware 全局异常捕获中间件
func globalPanicRecoveryMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				models.WrapResponse(c, 300, "系统异常-1", err, c.Err().Error())
				c.Abort()
				return
			}
		}()
		c.Next() // 调用下一个中间件或路由处理函数
	}
}
